package com.wlstock.funi.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.wlstock.funi.model.AIAccountsModel;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.TradeHisModel;
import com.wlstock.funi.utils.CaculateUtils;

public class TradeHisDao {
	
	private DataBaseHelper dbHelper;
	private static TradeHisDao daoInstance;
	private Dao<TradeHisModel, Integer> tradeHisDao;
	
	@SuppressWarnings("unchecked")
	private TradeHisDao(Context mContext){
		try {
			dbHelper = DataBaseHelper.getHelper(mContext);
			tradeHisDao = dbHelper.getDao(TradeHisModel.class);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static TradeHisDao getInstance(Context mContext){
		if (daoInstance == null) {
			synchronized (TradeHisDao.class) {
				if (daoInstance == null) {
					daoInstance = new TradeHisDao(mContext);
				}
			}
		}
		return daoInstance;
	}


	public void addBUYModel(AIAccountsModel aiModel) {
		TradeHisModel tradeModel = new TradeHisModel();
		tradeModel.setWithAIModel(aiModel);
		tradeModel.setStkQty(aiModel.getStkQty());
		tradeModel.setTradeType(OperateModel.TradeType_BUY);
		try {
			tradeHisDao.create(tradeModel);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void addSAILEModel(AIAccountsModel aiModel){
		long linkId = aiModel.getLinkId();
		try {
			TradeHisModel tmpModel = tradeHisDao.queryBuilder().where().eq("linkId", linkId).and().eq("stkName", aiModel.getStkName()).queryForFirst();
			if (tmpModel!=null && tmpModel.getCostPrice()!=null) {
				tmpModel.setProfitRate(CaculateUtils.getFloatDis(aiModel.getCurPrice(), tmpModel.getCostPrice()));
				tmpModel.setStkQty(aiModel.getStkQty());
				//计算利润
				tmpModel.setProfitMoney(tmpModel.getProfitRate()/100*tmpModel.getStkQty());
				tmpModel.setTradeType(OperateModel.TradeType_SELL);
				tradeHisDao.create(tmpModel);	
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 根据时间查询his纪录
	 * @return
	 */
	public List<TradeHisModel> queryHisDatasOrderbyDate() {
		List<TradeHisModel> result = new ArrayList<TradeHisModel>();
		try {
			result = tradeHisDao.queryBuilder().orderBy("createDate", true).query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	
}
